package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.common.utils.ConstantUtil;
import com.kingyun.gpsinspection.purificationservice.common.utils.FileTypeUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.*;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.RedisValue;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.*;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.CheckRepairService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.IBMBPMService;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.WorkOrderService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 检查维修业务层
 * Created by sugongche on 2017/1/15.
 */
public class CheckRepairServiceImpl implements CheckRepairService {
    public Logger logger = LoggerFactory.getLogger(this.getClass());

    // BPM
    @Autowired
    public IBMBPMService ibmbpmService;
    @Autowired
    public TaskLinkMapper taskLinkMapper;
    @Autowired
    private CheckRepairMapper checkRepairMapper;
    @Autowired
    private TdmFileMapper tdmFileMapper;
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private TdmTaskRelationMapper tdmTaskRelationMapper;
    @Autowired
    public TdmWorkOrderMapper tdmWorkOrderMapper;
    @Autowired
    public WorkOrderEmployeeMapper workOrderEmployeeMapper;


    /**
     * 保存
     * 注意：解开启事务，不能抛异常
     *
     * @param redisValue
     * @param employeeVo
     * @param checkRepair
     * @param workOrderList
     * @param taskRelation
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int save(RedisValue redisValue, EmployeeVo employeeVo, CheckRepair checkRepair, String uploadFiles, String deletedFiles, List<WorkOrderVo> workOrderList, TaskRelation taskRelation) {
        if (checkRepair == null) {
            return 0;
        }

        int a = 0;

        //String username = "deadmin";
        //String password = "deadmin";
        String username = redisValue.getLoginName();
        String password = redisValue.getPassWord();
        //开始流程
        String result = ibmbpmService.openBPM(employeeVo, checkRepair.getTaskType(), username, password, null);
        //如果没有权限直接返回99
        if (result.equals("WorkSpaceError")) {
            return 99;
        }
        String piid = "";//流程实例ID
        String tkiid = "";//任务节点ID
        String name = ""; //第一个任务实例节点的名称

        //获得返回值
        JSONObject resultObj = JSONObject.parseObject(result);
        if (resultObj != null) {
            String status = (String) resultObj.get("status");
            //开始流程成功
            if (status != null && status.equals("200")) {
                //获取data属性的值
                JSONObject dataObj = (JSONObject) resultObj.get("data");
                //获取tasks属性的值：只有一个元素的数组，元素包含流程实例id和第一个节点的任务id
                JSONArray itemsArray = (JSONArray) dataObj.get("tasks");
                for (int i = 0; i < itemsArray.size(); i++) {//循环json数组
                    JSONObject ob = (JSONObject) itemsArray.get(i);//得到json对象
                    piid = ob.getString("piid");//piid这里是列名称，获取json对象中列名为piid的值
                    tkiid = ob.getString("tkiid");//tkiid这里是列名称，获取json对象中列名为tkiid的值
                    name = ob.getString("name");//name是列名称，获取json对象中列名为name的值
                }

                //执行第一个任务节点
                result = ibmbpmService.completeTask(username, password, tkiid, null);
                //获得返回值
                resultObj = JSONObject.parseObject(result);
                if (resultObj != null && !"".equals(resultObj)) {
                    status = (String) resultObj.get("status");

                    //完成任务成功
                    if (status != null && status.equals("200")) {
                        //第一步：保存任务信息
                        //新增发起任务信息：必须设置流程实例ID
                        checkRepair.setFlowId(piid);
                        //当前节点：从0开始
                        checkRepair.setNode((short) 0);
                        a = saveBean(employeeVo, checkRepair);
                        // 判断关联任务对象是否为空
                        if (StringUtils.isNotBlank(taskRelation.getMasterTaskId())) {
                            // 关系表主键
                            taskRelation.setTaskRelationId(UniqueUtil.uuid());
                            // 主任务ID和主任务类型已经包含在relation对象中
                            taskRelation.setRelatedTaskId(checkRepair.getCheckRepairId());
                            taskRelation.setRelatedTaskType(checkRepair.getTaskType());
                            // 保存关联任务信息
                            tdmTaskRelationMapper.insert(taskRelation);
                        }

                        //第二步：保存附件：根据任务信息
                        a += saveAttach(checkRepair, uploadFiles, deletedFiles);

                        //第三步：保存任务环节和工单
                        TaskLink taskLink = new TaskLink();
                        taskLink.setPiPiid(piid);//流程实例ID
                        taskLink.setTkiid(tkiid);//任务节点ID
                        taskLink.setTaskLinkName(name); //任务节点名称
                        //第一个节点默认通过
                        taskLink.setAuditStatus((short) 1);

                        //保存任务相关信息：先保存任务节点信息，后保存工单信息
                        a += saveTaskLinkWorkOrder(employeeVo, checkRepair, taskLink, workOrderList);
                    } else {
                        logger.error("完成检查维修流程第一个任务节点失败！");
                    }
                } else {
                    logger.error("完成检查维修流程第一个任务节点无返回值！");
                }

            } else {
                logger.error("发起检查维修流程失败！");
            }
        } else {
            logger.error("发起检查维修流程无返回值！");
        }

        return a;
    }

    /**
     * 保存检查维修任务对象
     *
     * @param employeeVo
     * @param checkRepair
     * @return
     */
    public int saveBean(EmployeeVo employeeVo, CheckRepair checkRepair) {
        int a = 0;

        checkRepair.setCheckRepairId(UniqueUtil.uuid());
        checkRepair.setCreateUserId(employeeVo.getEmployeeId());
        checkRepair.setModifyUserId(employeeVo.getEmployeeId());
        //-1 正在审核；1 审核通过；0审核不通过
        checkRepair.setAuditStatus((short) -1);
        //状态0正常；1是删除
        checkRepair.setIsDelete((short) 0);
        //状态1是启用；0是关闭
        checkRepair.setIsEnable((short) 1);
        //1 审核处理中；2 执行中；3 已完成
        checkRepair.setTaskStatus((short) 1);
        //创建时间
        checkRepair.setCreateTime(new Date());
        //修改时间
        checkRepair.setModifyTime(new Date());
        a = checkRepairMapper.insert(checkRepair);

        return a;
    }

    /**
     * 根据Bean的信息保存附件（新增和删除）
     *
     * @param checkRepair
     * @param uploadFiles
     * @return
     */
    public int saveAttach(CheckRepair checkRepair, String uploadFiles, String deletedFiles) {
        int a = 0;

        //保存附件
        if (StringUtils.isNotBlank(uploadFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);
            //重新设置附件属性
            for (int i = 0; i < listFiles.size(); i++) {
                File _file = listFiles.get(i);
                //设置主键
                _file.setFileId(UniqueUtil.uuid());
                //设置业务数据id
                _file.setBusinessId(checkRepair.getCheckRepairId());
                _file.setFileType((short) FileTypeUtil.getFileTypeByFileName(_file.getFileName()));
            }
            //必须判断非空
            if (listFiles != null && listFiles.size() > 0) {
                a = tdmFileMapper.insertByList(listFiles);
            }
        }

        //需要删除的附件信息
        if (StringUtils.isNotBlank(deletedFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(deletedFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    a += tdmFileMapper.deleteByPrimaryKey(_file.getFileId());
                }
            }
        }

        return a;
    }

    /**
     * 根据任务信息保存工单
     *
     * @param employeeVo
     * @param checkRepair
     * @param workOrderList
     * @return
     */
    public int saveWorkOrderList(EmployeeVo employeeVo, CheckRepair checkRepair, List<WorkOrderVo> workOrderList) {
        int a = 0;

        if (workOrderList != null && workOrderList.size() > 0) {
            //注意思路：先删除后新增
            List<WorkOrder> oldWorkOrderList = tdmWorkOrderMapper.findListByTaskId(checkRepair.getCheckRepairId());

            //先根据工单Id删除工单和人员的关系表
            if (oldWorkOrderList != null && oldWorkOrderList.size() > 0) {
                for (WorkOrder oldWorkOrder : oldWorkOrderList) {
                    if (oldWorkOrder != null && oldWorkOrder.getWorkOrderId() != null) {
                        a += workOrderEmployeeMapper.deleteByWorkOrderId(oldWorkOrder.getWorkOrderId());
                    }
                }
            }

            //再根据任务Id删除该任务对应的工单：
            a += tdmWorkOrderMapper.deleteByTaskId(checkRepair.getCheckRepairId());

            //重要方法：给List中的元素回设置
            for (WorkOrderVo workOrder : workOrderList) {
                //重新设置主键ID
                workOrder.setWorkOrderId(UniqueUtil.uuid());
                workOrder.setTaskId(checkRepair.getCheckRepairId());
                //无法保存任务环节ID
                //workOrder.setTaskLinkId();
                workOrder.setTaskType(checkRepair.getTaskType());
                workOrder.setCreateUserId(employeeVo.getEmployeeId());
                workOrder.setModifyUserId(employeeVo.getEmployeeId());
                //工单状态：-1预处理，0创建，1作业条件检查，2作业前准备，3操作申请（关键操作--才会申请），4审核通过，5审核不通过，6已经完成，7已关闭
                workOrder.setStatus((short) -1);
                //1是删除；0是正常
                workOrder.setIsDelete((short) 0);
                //0未下载；已经下载
                workOrder.setIsDownload((short) 0);
                //0无法完成；1可以完成
                workOrder.setCanFinish((short) 1);
                //0未确认；1已经确认
                workOrder.setConfirmStatus((short) 0);

                //先保存工单
                a += tdmWorkOrderMapper.insertNew(workOrder);

                //保存工单和人员的关系表：
                if (workOrder.getUserId() != null) {
                    String[] array = workOrder.getUserId().split(",");

                    if (array != null && array.length > 0) {
                        for (int i = 0; i < array.length; i++) {
                            if (StringUtils.isNotBlank(array[i])) {
                                WorkOrderEmployee workOrderEmployee = new WorkOrderEmployee();
                                workOrderEmployee.setWorkOrderEmployeeId(UniqueUtil.uuid());
                                workOrderEmployee.setWorkOrderId(workOrder.getWorkOrderId());
                                workOrderEmployee.setEmployeeId(array[i]);

                                a += workOrderEmployeeMapper.insert(workOrderEmployee);
                            }

                        }
                    }

                }

            }
        }

        return a;
    }

    /**
     * 更新
     *
     * @param redisValue
     * @param employeeVo
     * @param checkRepair
     * @param taskLink
     * @param workOrderVoList @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int update(RedisValue redisValue, EmployeeVo employeeVo, CheckRepair checkRepair, TaskLink taskLink, String uploadFiles, String deletedFiles, List<WorkOrderVo> workOrderVoList) {
        if (checkRepair == null) {
            return 0;
        }

        //标志变量
        int a = 0;

        //String username="deadmin";
        //String password="deadmin";

        String username = redisValue.getLoginName();//用户名
        String password = redisValue.getPassWord();//密码
        String result = ibmbpmService.completeTask(username, password, taskLink.getTkiid(), null);

        //处理返回值为空串：执行了但是没有返回值
        if ("".equals(result)) {
            logger.info("完成“" + taskLink.getTaskLinkName() + "”返回值为空串！");
        } else {
            //获得返回值
            JSONObject resultObj = JSONObject.parseObject(result);
            if (resultObj != null) {
                String status = (String) resultObj.get("status");
                //开始流程成功
                if (status != null && status.equals("200")) {
                    //第一步：更新任务信息；修改人必填
                    checkRepair.setModifyUserId(employeeVo.getEmployeeId());
                    a += checkRepairMapper.updateByPrimaryKeyNew(checkRepair);

                    //第二步：更新附件信息：新增+删除
                    a += saveAttach(checkRepair, uploadFiles, deletedFiles);

                    //第三步：更新工单信息
                    a += updateWorkOrder(employeeVo, checkRepair, taskLink, workOrderVoList);

                    //第四步：更新任务环节信息；工单信息已经更新：此处无需再保存工单
                    //注意：必须拿到当前任务的信息，因为从页面上传来的任务信息没有node值
                    CheckRepair checkRepairNew = checkRepairMapper.selectByPrimaryKey(checkRepair.getCheckRepairId());
                    a += saveTaskLinkWorkOrder(employeeVo, checkRepairNew, taskLink, null);
                } else {
                    logger.error("完成“" + taskLink.getTaskLinkName() + "”返回状态非200！");
                }
            } else {
                logger.error("完成“" + taskLink.getTaskLinkName() + "”返回值非json字符串！！");
            }
        }

        return a;
    }

    /**
     * 更新任务的工单
     *
     * @param employeeVo
     * @param checkRepair
     * @param workOrderVoList
     * @return
     */
    public int updateWorkOrder(EmployeeVo employeeVo, CheckRepair checkRepair, TaskLink taskLink, List<WorkOrderVo> workOrderVoList) {
        if (checkRepair == null) {
            return 0;
        }

        int a = 0;
        //注意思路：先删除后新增
        //删除该任务在数据库已有的工单
        a += tdmWorkOrderMapper.deleteByTaskId(checkRepair.getCheckRepairId());
        //保存页面的工单
        a += workOrderService.saveWorkOrderList(employeeVo, taskLink, workOrderVoList);

        return a;
    }

    /**
     * 根据主键查询bean
     *
     * @param checkRepairId
     * @return
     */
    @Override
    public CheckRepair queryBeanById(String checkRepairId) throws Exception {
        if (StringUtils.isBlank(checkRepairId)) {
            return null;
        }

        CheckRepair checkRepair = checkRepairMapper.selectByPrimaryKey(checkRepairId);

        return checkRepair;
    }

    /**
     * 根据主键查询包装类
     *
     * @param checkRepairId
     * @return
     */
    @Override
    public CheckRepairVo queryVoById(String checkRepairId) throws Exception {
        if (StringUtils.isBlank(checkRepairId)) {
            return null;
        }

        CheckRepairVo checkRepairVo = checkRepairMapper.selectByPrimaryKeyNew(checkRepairId);

        return checkRepairVo;
    }

    /**
     * 根据任务实例ID查询任务表和任务环节表
     *
     * @param piPiid
     * @return
     */
    @Override
    public CheckRepairVo findByVoPiPiid(String piPiid) {
        if (StringUtils.isBlank(piPiid)) {
            return null;
        }

        CheckRepairVo checkRepairVo = checkRepairMapper.findVoByPiPiid(piPiid);

        return checkRepairVo;
    }

    /**
     * 审核
     *
     * @param redisValue
     * @param employeeVo
     * @param taskLink
     * @param workOrderList
     * @param checkRepair
     * @return
     */
    @Override
    public int saveByAudit(RedisValue redisValue, EmployeeVo employeeVo, TaskLink taskLink, List<WorkOrderVo> workOrderList, CheckRepair checkRepair) {
        if (taskLink == null) {
            return 0;
        }

        //用户信息
        //String username = "deadmin";
        //String password = "deadmin";
        String username = redisValue.getLoginName();//用户名
        String password = redisValue.getPassWord();//密码

        String parameter = null;
        try {
            if (taskLink.getAuditStatus() != null && taskLink.getIsImportant() == null) {
                //获取前台页面传来的审核是否通过的值：是用taskLink接收的
                parameter = URLEncoder.encode("{\"approved\":" + taskLink.getAuditStatus() + "}", "UTF-8");
            } else if (taskLink.getAuditStatus() != null && taskLink.getIsImportant() != null) {
                parameter = URLEncoder.encode("{\"approved\":" + taskLink.getAuditStatus() + ",\"isImportant\":" + taskLink.getIsImportant() + "}", "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("格式化输入参数错误", e);
        }
        String result = ibmbpmService.completeTask(username, password, taskLink.getTkiid(), parameter);

        //标志变量
        int a = 0;
        //处理返回值为空串：执行了但是没有返回值
        if ("".equals(result)) {
            logger.info("完成“" + taskLink.getTaskLinkName() + "”返回值为空串！");
        } else {
            //获得返回值
            JSONObject resultObj = JSONObject.parseObject(result);
            if (resultObj != null) {
                String status = (String) resultObj.get("status");
                //开始流程成功
                if (status != null && status.equals("200")) {
                    a = saveTaskLinkWorkOrder(employeeVo, checkRepair, taskLink, workOrderList);
                } else {
                    logger.error("完成“" + taskLink.getTaskLinkName() + "”返回状态非200！");
                }
            } else {
                logger.error("完成“" + taskLink.getTaskLinkName() + "”返回值非json字符串！！");
            }
        }

        return a;
    }

    /**
     * 接受并分发检查维修计划，现场操作，确认，恢复生产
     *
     * @param employeeVo
     * @param checkRepair
     * @param taskLink
     * @return
     */
    @Override
    public int saveByStep(RedisValue redisValue, EmployeeVo employeeVo, CheckRepair checkRepair, TaskLink taskLink) {
        if (taskLink == null) {
            return 0;
        }

        //用户信息
        //String username = "deadmin";
        //String password = "deadmin";
        String username = redisValue.getLoginName();//用户名
        String password = redisValue.getPassWord();//密码
        String result = ibmbpmService.completeTask(username, password, taskLink.getTkiid(), null);

        //标志变量
        int a = 0;
        //处理返回值为空串：执行了但是没有返回值
        if ("".equals(result)) {
            logger.info("完成“" + taskLink.getTaskLinkName() + "”返回值为空串！");
        } else {
            //获得返回值
            JSONObject resultObj = JSONObject.parseObject(result);
            if (resultObj != null) {
                String status = (String) resultObj.get("status");
                //开始流程成功
                if (status != null && status.equals("200")) {
                    a = saveTaskLinkWorkOrder(employeeVo, checkRepair, taskLink, null);
                } else {
                    logger.error("完成“" + taskLink.getTaskLinkName() + "”返回状态非200！");
                }
            } else {
                logger.error("完成“" + taskLink.getTaskLinkName() + "”返回值非json字符串！");
            }
        }

        return a;
    }

    /**
     * 保存任务相关信息：先保存任务节点信息，后保存工单信息
     *
     * @param employeeVo
     * @param checkRepair
     * @param taskLink
     * @param workOrderList
     * @return
     */
    public int saveTaskLinkWorkOrder(EmployeeVo employeeVo, CheckRepair checkRepair, TaskLink taskLink, List<WorkOrderVo> workOrderList) {
        //标志变量
        int a = 0;

        //表单提交的审核状态
        Short auditStatus = taskLink.getAuditStatus();

        //第一步：添加任务环节
        taskLink.setTaskLinkId(UniqueUtil.uuid());
        //任务发起表存的是当前节点
        taskLink.setNode(checkRepair.getNode());
        taskLink.setTaskType(checkRepair.getTaskType());
        taskLink.setTaskId(checkRepair.getCheckRepairId());
        //执行人ID：当前用户ID
        taskLink.setUserId(employeeVo.getEmployeeId());
        //执行人组织
        taskLink.setOrgId(employeeVo.getOrgId());
        //没有审核：完成任务默认审核通过
        taskLink.setAuditStatus(auditStatus == null ? (short) 1 : auditStatus);
        a += taskLinkMapper.insertNew(taskLink);

        //第二步：修改工单
        a += workOrderService.saveWorkOrderList(employeeVo, taskLink, workOrderList);
        //没有审核：走到下一个节点，审核状态默认为通过
        if (auditStatus == null) {
            //更新当前状态
            checkRepair.setAuditStatus((short) 1);
            a += checkRepairMapper.updateAuditStatusById(checkRepair);
            //审核通过
        } else if (auditStatus != null && auditStatus == 1) {
            //更新当前状态
            checkRepair.setAuditStatus((short) 1);
            a += checkRepairMapper.updateAuditStatusById(checkRepair);
            //驳回：回到第一个节点
        } else if (auditStatus != null && auditStatus == 0) {
            //更新当前状态
            checkRepair.setAuditStatus((short) 0);
            a += checkRepairMapper.updateAuditStatusById(checkRepair);
        }

        //进入现场操作：必须结合下面两个条件
        if (auditStatus != null && auditStatus == 1 && ConstantUtil.CONFIRM.equals(taskLink.getTaskLinkName())) {
            //更新任务状态：执行中,所有工单状态改为可下载
            a += checkRepairMapper.updateTaskStatusExecutedById(checkRepair);
            //更新工单状态：为待处理
            a += tdmWorkOrderMapper.updateStatusEnableByTaskId(checkRepair.getCheckRepairId());
        }

        //完成任务时：更新任务状态和实际完成时间
        //if (ConstantUtil.CONFIRM.equals(taskLink.getTaskLinkName())) {
        //    a += checkRepairMapper.updateFinishById(checkRepair);
        //}

        return a;
    }

    /**
     * 新建分析处理关联的检查维修任务：不走BPM
     *
     * @param employeeVo
     * @param checkRepair
     * @param uploadFiles
     * @param deletedFiles
     * @param workOrderList
     * @param analysisProcessId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int saveRelation(EmployeeVo employeeVo, CheckRepair checkRepair, String uploadFiles, String deletedFiles, List<WorkOrderVo> workOrderList, String analysisProcessId) {
        if (checkRepair == null) {
            return 0;
        }

        int a = 0;
        checkRepair.setNode((short) -1);
        //注意对象做方法参数传的是引用：此方法中设置的值，在此方法结束后，相应对象的值也改变
        a += saveBean(employeeVo, checkRepair);

        TaskRelation taskRelation = new TaskRelation();
        taskRelation.setTaskRelationId(UniqueUtil.uuid());
        taskRelation.setMasterTaskId(analysisProcessId);
        taskRelation.setMasterTaskType((short) 5);
        taskRelation.setRelatedTaskId(checkRepair.getCheckRepairId());
        taskRelation.setRelatedTaskType(checkRepair.getTaskType());
        a += tdmTaskRelationMapper.insert(taskRelation);

        //根据任务信息保存工单
        a += saveWorkOrderList(employeeVo, checkRepair, workOrderList);
        //根据任务信息保存附件
        a += saveAttach(checkRepair, uploadFiles, deletedFiles);

        return a;
    }

    /**
     * 修改分析处理关联的检查维修任务页面：不走BPM
     *
     * @param employeeVo
     * @param checkRepair
     * @param uploadFiles
     * @param deletedFiles
     * @param workOrderList
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int updateRelation(EmployeeVo employeeVo, CheckRepair checkRepair, String uploadFiles, String deletedFiles, List<WorkOrderVo> workOrderList) {
        if (checkRepair == null) {
            return 0;
        }

        //标志变量
        int a = 0;

        //第一步：更新任务信息；修改人必填
        checkRepair.setModifyUserId(employeeVo.getEmployeeId());
        a += checkRepairMapper.updateByPrimaryKeyNew(checkRepair);

        //第二步：更新附件信息：新增+删除
        a += saveAttach(checkRepair, uploadFiles, deletedFiles);

        //第三步：更新工单信息：先删除，后新增
        a += saveWorkOrderList(employeeVo, checkRepair, workOrderList);

        return a;
    }


    /**
     * 发起BPM流程：和save方法相似
     *
     * @param redisValue
     * @param employeeVo
     * @param checkRepair
     * @param workOrderVoList
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int launchBPM(RedisValue redisValue, EmployeeVo employeeVo, CheckRepair checkRepair, List<WorkOrderVo> workOrderVoList) {
        int a = 0;

        //String username = "deadmin";
        //String password = "deadmin";

        String username = redisValue.getLoginName();//用户名
        String password = redisValue.getPassWord();//密码
        //开始流程：需要任务类型
        String result = ibmbpmService.openBPM(employeeVo, checkRepair.getTaskType(), username, password, null);
        //如果没有权限直接返回99
        if (result.equals("WorkSpaceError")) {
            return 99;
        }
        String piid = "";//流程实例ID
        String tkiid = "";//任务节点ID
        String name = ""; //第一个任务实例节点的名称

        //获得返回值
        JSONObject resultObj = JSONObject.parseObject(result);
        if (resultObj != null) {
            String status = (String) resultObj.get("status");
            //开始流程成功
            if (status != null && status.equals("200")) {
                //获取data属性的值
                JSONObject dataObj = (JSONObject) resultObj.get("data");
                //获取tasks属性的值：只有一个元素的数组，元素包含流程实例id和第一个节点的任务id
                JSONArray itemsArray = (JSONArray) dataObj.get("tasks");
                for (int i = 0; i < itemsArray.size(); i++) {//循环json数组
                    JSONObject ob = (JSONObject) itemsArray.get(i);//得到json对象
                    piid = ob.getString("piid");//piid这里是列名称，获取json对象中列名为piid的值
                    tkiid = ob.getString("tkiid");//tkiid这里是列名称，获取json对象中列名为tkiid的值
                    name = ob.getString("name");//name是列名称，获取json对象中列名为name的值
                }

                //执行第一个任务节点
                result = ibmbpmService.completeTask(username, password, tkiid, null);
                //获得返回值
                resultObj = JSONObject.parseObject(result);
                if (resultObj != null && !"".equals(resultObj)) {
                    status = (String) resultObj.get("status");
                    //完成任务成功
                    if (status != null && status.equals("200")) {
                        //第一步：更新流程实例ID和当前节点
                        checkRepair.setFlowId(piid);
                        checkRepair.setNode((short) 0);
                        //CREATE_TIME重新赋值：代表任务发起时间，而不是任务新建时间
                        checkRepair.setCreateTime(new Date());
                        a += checkRepairMapper.updateByPrimaryKeySelective(checkRepair);

                        //第二步：保存任务环节；修改工单需要保存；
                        TaskLink taskLink = new TaskLink();
                        taskLink.setPiPiid(piid);//流程实例ID
                        taskLink.setTkiid(tkiid);//任务节点ID
                        taskLink.setTaskLinkName(name); //任务节点名称
                        //第一个节点默认通过
                        taskLink.setAuditStatus((short) 1);
                        //任务指派人可以修改工单，但不能修改任务基础信息
                        a += saveTaskLinkWorkOrder(employeeVo, checkRepair, taskLink, workOrderVoList);
                    } else {
                        logger.error("完成检查维修流程第一个任务节点失败！");
                    }
                } else {
                    logger.error("完成检查维修流程第一个任务节点无返回值！");
                }

            } else {
                logger.error("发起检查维修流程失败！");
            }
        } else {
            logger.error("发起检查维修流程无返回值！");
        }

        return a;
    }
}
